<template>
  <div style="margin: 15px">
    <el-form :model="selectArticle" ref="selectStudent" class="demo-dialogForm" v-show="toggle"
             label-width="70px" inline>
      <el-form-item label="标题" prop="title" size="medium">
        <el-input v-model="selectArticle.title" clearable placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="state" size="medium">
        <el-select v-model="selectArticle.state" clearable placeholder="请选择状态">
          <el-option label="草稿" :value="0"></el-option>
          <el-option label="已上线" :value="1"></el-option>
          <el-option label="已下线" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="作者" prop="author" size="medium">
        <el-input v-model="selectArticle.author" clearable placeholder="请输入作者"></el-input>
      </el-form-item>
      <el-form-item label="分类" prop="categoryId" size="medium">
        <el-select v-model="selectArticle.categoryId" clearable placeholder="请选择分类">
          <el-option v-for="item in category" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="发布时间" prop="publishTime" size="medium">
        <el-date-picker
          v-model="publishTime"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="selectList" size="mini">搜索
        </el-button>
        <el-button icon="el-icon-refresh" @click="reset" size="mini">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row>
      <el-button icon="el-icon-plus" plain type="primary" @click="insertHandler" size="mini">新增</el-button>
      <el-button icon="el-icon-delete" plain type="danger" @click="deleteHandler" size="mini"
                 :disabled="ids.length===0">删除
      </el-button>
      <div class="right-toolbar">
        <el-tooltip class="item" effect="dark" :content="toggle?'隐藏搜索':'显示搜索'" placement="top">
          <el-button size="mini" circle icon="el-icon-search" @click="toggle=!toggle"/>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="selectList"/>
        </el-tooltip>
      </div>
    </el-row>

    <el-table :data="articles" tooltip-effect="dark" style="width: 100%;margin-top: 15px" :header-cell-style="style"
              @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="50"></el-table-column>
      <el-table-column align="center" prop="id" label="ID" width="60"></el-table-column>
      <el-table-column align="center" prop="title" label="标题">
        <template slot-scope="scope">
          <el-link type="primary" @click="goto(scope.row)">{{ scope.row.title }}</el-link>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="content" label="内容" show-overflow-tooltip width="100"></el-table-column>
      <el-table-column align="center" prop="state" label="状态" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.state===0">草稿</el-tag>
          <el-tag type="success" v-if="scope.row.state===1">已上线</el-tag>
          <el-tag type="warning" v-if="scope.row.state===2">已下线</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="author" label="作者" width="60"></el-table-column>
      <el-table-column align="center" prop="categoryId" label="分类" width="80">
        <template slot-scope="scope">
          <p v-for="item in category" v-if="scope.row.categoryId===item.id">{{ item.name }}</p>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="publishTime" label="发布时间" width="160"></el-table-column>
      <el-table-column align="center" label="操作" width="180">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-download" size="mini" @click="changeRow(scope.row,'down')"
                     v-show="scope.row.state===1">下线
          </el-button>
          <el-button type="text" icon="el-icon-upload2" size="mini" @click="changeRow(scope.row,'up')"
                     v-show="scope.row.state!==1">上线
          </el-button>
          <el-button type="text" icon="el-icon-edit" size="mini" @click="updateRow(scope.row)"
                     v-show="scope.row.state!==1">修改
          </el-button>
          <el-button type="text" icon="el-icon-delete" size="mini" @click="deleteRow(scope.row)"
                     v-show="scope.row.state!==1">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[5, 20, 50, 100]"
      :page-size="pageSize"
      layout="->,total, sizes, prev, pager, next, jumper"
      :total="totalPage">
    </el-pagination>

    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="800px">
      <el-form :model="form" label-width="80px" :rules="rules" ref="form">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <quill-editor v-model="form.content"/>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="form.state" placeholder="请选择状态">
            <el-option label="草稿" :value="0"></el-option>
            <el-option label="已上线" :value="1"></el-option>
            <el-option label="已下线" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择状态">
            <el-option v-for="item in category" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker
            v-model="form.publishTime"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="请选择毕业日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {deleteList, editList, getList, getState} from "@/api/blog/article";
import {id} from "html-webpack-plugin/lib/chunksorter";

export default {
  name: "文章",
  data() {
    return {
      toggle: true,
      category: [],
      selectArticle: {
        id: null,
        title: null,
        state: null,
        author: null,
        categoryId: null,
        publishStartTime: '',
        publishEndTime: ''
      },
      publishTime: [],
      articles: [],
      ids: [],
      pageNum: 1,
      pageSize: 5,
      totalPage: 0,
      title: null,
      dialogFormVisible: false,
      form: {
        title: null,
        content: null,
        state: null,
        author: null,
        categoryId: null,
        publishTime: null
      },
      rules: {
        title: {required: true, message: '标题不能为空', trigger: 'blur'},
        author: {required: true, message: '作者不能为空', trigger: 'blur'}
      },
      method: null
    }
  },
  created() {
    this.getStateFromCategory()
    this.selectList()
  },
  methods: {
    style() {
      return "background-color:RGB(248,248,249);color:RGB(81,90,110)"
    },
    getStateFromCategory() {
      getState().then(res => {
        console.log(res)
        this.category = res.data.list
      })
    },
    selectList() {
      const body = this.selectArticle
      body.pageNum = this.pageNum
      body.pageSize = this.pageSize
      body.publishStartTime = this.publishTime[0]
      body.publishEndTime = this.publishTime[1]
      getList(body).then(res => {
        console.log(res)
        this.articles = res.data.list
        this.totalPage = res.data.count
      })
    },
    deleteHandler() {
      this.$confirm('是否确认删除文章管理编号为"' + this.ids + '"的数据项？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteList(this.ids).then(() => {
          this.$message.success("删除成功")
          this.selectList()
        }).catch(err => {
          this.$message.error(err.msg || "删除失败")
        })
      })
    },
    deleteRow(row) {
      this.$confirm('是否确认删除文章管理编号为"' + row.id + '"的数据项？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteList(row.id).then(() => {
          this.$message.success("删除成功")
          this.selectList()
        }).catch(err => {
          this.$message.error(err.msg || "删除失败")
        })
      })
    },
    insertHandler() {
      this.title = "添加文章管理"
      this.method = "post"
      this.dialogFormVisible = true
      this.clear()
    },
    updateRow(row) {
      this.title = "修改文章管理"
      this.method = "put"
      this.dialogFormVisible = true
      this.clear(row)
    },
    changeRow(row, s) {
      this.$confirm('确认要下线《' + row.title + '》文章吗？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.success(this.form.state = s === 'down' ? "下线成功" : "上线成功")
        this.method = 'put'
        this.form = JSON.parse(JSON.stringify(row))
        this.form.state = s === 'down' ? 2 : 1
        this.submit("change")
      })
    },
    clear(data) {
      this.form = this.$options.data().form
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        this.$refs.form.clearValidate()
        if (this.method === 'put') {
          this.form = JSON.parse(JSON.stringify(data))
        }
      })
    },
    submit(s) {
      this.$refs.form.validate((valid) => {  //开启校验
        if (valid) {   // 如果校验通过，请求接口，允许提交表单
          const msg = this.method === 'post' ? "新增" : "修改"
          editList(this.method, this.form).then(() => {
            if (!s) this.$message.success(msg + "成功")
          }).finally(() => {
            this.selectList()
            this.$nextTick(() => {
              this.$refs.form.resetFields();
            })
            this.$refs.form.clearValidate();
            this.dialogFormVisible = false
          })
        }
      })
    },
    reset() {
      this.selectArticle = {}
      this.publishTime = []
      this.selectList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.ids = this.multipleSelection.map(i => i.id)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.selectList()
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this.selectList()
      // console.log(`当前页: ${val}`);
    },
    goto(row) {
      this.$router.push("article-view/article/" + row.id)
    }
  }
}
</script>

<style scoped lang="scss">
.right-toolbar {
  float: right;
}
</style>
